/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.una.scece.servicios;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import com.una.scece.clases.Persona;
import com.una.scece.control.controlGestor;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Erick
 */
@WebServlet(name = "servicioPersona", urlPatterns = {"/servicioPersona"})
public class servicioPersona extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            String accion = request.getParameter("accion");
            if (accion.equalsIgnoreCase("agregarEstudiante")) {
                this.guardarPersonaEstudiante(request, response);
            } else if (accion.equalsIgnoreCase("agregarFuncionario")) {
                this.guardarPersonaFuncionario(request, response);
            } else if (accion.equalsIgnoreCase("eliminarPersona")) {
                this.eliminarPersona(request, response);
            } else if (accion.equalsIgnoreCase("buscarPersona")) {
                this.buscarPersona(request, response);
            } else if (accion.equalsIgnoreCase("cargarPersona")) {
                this.cargarPersona(request, response);
            } else if (accion.equalsIgnoreCase("modificarPersona")) {
                this.actualizarPersona(request, response);
            } else if (accion.equalsIgnoreCase("listarPersona")) {
                this.listarPersona(request, response);
            }
        } finally {
        }
    }

    private void guardarPersonaEstudiante(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text");
        PrintWriter out = response.getWriter();
        String identificacion = request.getParameter("identificacion");
        String nombre = request.getParameter("nombreCompleto");
        Date fecha = Date.valueOf(request.getParameter("fechaNacimiento"));
        String telHabitacion = request.getParameter("telHabitacion");
        String telOficina = request.getParameter("telOficina");
        String telCelular = request.getParameter("telCelular");
        String correo = request.getParameter("correo");
        String direccion = request.getParameter("direccion");
        Persona persona = new Persona(identificacion, nombre, fecha, telHabitacion, telOficina, telCelular, correo, direccion, 1);
        try {
            Thread.sleep(1000);
            controlGestor.guardarPersona(persona);
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    private void guardarPersonaFuncionario(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text");
        PrintWriter out = response.getWriter();
        String identificacion = request.getParameter("identificacion");
        String nombre = request.getParameter("nombreCompleto");
        Date fecha = Date.valueOf(request.getParameter("fechaNacimiento"));
        String telHabitacion = request.getParameter("telHabitacion");
        String telOficina = request.getParameter("telOficina");
        String telCelular = request.getParameter("telCelular");
        String correo = request.getParameter("correo");
        String direccion = request.getParameter("direccion");
        Persona persona = new Persona(identificacion, nombre, fecha, telHabitacion, telOficina, telCelular, correo, direccion, 2);
        try {
            controlGestor.guardarPersona(persona);
            out.println("Agregado Correctamente");
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            out.println("Imposible Agregar");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
        }
    }

    private void eliminarPersona(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text");
        PrintWriter out = response.getWriter();
        String identificacion = request.getParameter("identificacion");
        Persona persona = new Persona();
        persona.setIdentificacion(identificacion);
        try {
            controlGestor.eliminarPersona(persona);
            response.setStatus(HttpServletResponse.SC_OK);
            Thread.sleep(1000);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
        }
    }

    private void actualizarPersona(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/text");
        PrintWriter out = response.getWriter();
        Persona persona = new Persona();
        persona.setIdentificacion(request.getParameter("identificacion"));
        persona.setNombre(request.getParameter("nombreCompleto"));
        persona.setFechaNacimiento(Date.valueOf(request.getParameter("fechaNacimiento")));
        persona.setTelefonoHabitacion(request.getParameter("telHabitacion"));
        persona.setTelefonoOficina(request.getParameter("telOficina"));
        persona.setTelefonoCelular(request.getParameter("telCelular"));
        persona.setCorreoElectronico(request.getParameter("correo"));
        persona.setDireccion(request.getParameter("direccion"));
        try {
            controlGestor.actualizarPersona(persona);
            Thread.sleep(1000);
            out.println("Actualizado Correctamente");
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            out.println("Imposible actualizar");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
        }
    }

    private void buscarPersona(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String info = "";
        String identificacion = request.getParameter("identificacion");
        Persona persona = new Persona();
        persona.setIdentificacion(identificacion);
        try {
            controlGestor.buscarPersona(persona);
            response.setStatus(HttpServletResponse.SC_OK);
            info = "<div class=\"table\"> ";
            info += "<p><strong>Informaci&oacute;n</strong></p>"
                    + "<table class=\"listing\" cellpadding=\"0\" cellspacing=\"0\">";
            info += "<tr><th>Nombre Completo:&nbsp;</th><td width=\"75%\"><span>&nbsp;" + persona.getNombre() + "</span></td></tr>";
            info += "<tr><th>Fecha de Nacimiento:&nbsp;</th><td>&nbsp;" + String.valueOf(persona.getFechaNacimiento()) + "</td></tr>";
            info += "<tr><th>Tel&eacute;fono de Oficina:&nbsp;</th><td>&nbsp;" + persona.getTelefonoOficina() + "</td></tr>";
            info += "<tr><th>Tel&eacute;fono de Habitaci&oacute;n:&nbsp;</th><td>&nbsp;" + persona.getTelefonoHabitacion() + "</td></tr>";
            info += "<tr><th>Tel&eacute;fono Celular:&nbsp;</th><td>&nbsp;" + persona.getTelefonoCelular() + "</td></tr>";
            info += "<tr><th>Correo Electr&oacute;nico:&nbsp;</th><td>&nbsp;" + persona.getCorreoElectronico() + "</td></tr>";
            info += "<tr><th>Direcci&oacute;n:&nbsp;</th><td>&nbsp;" + persona.getDireccion() + "</td></tr></table>";
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            info = "";
            info = "<p><strong>No existen coincidencias</strong><p>";
        } finally {
            out.println(info);
            out.close();
        }


    }

    private void cargarPersona(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String info = "";
        String identificacion = request.getParameter("identificacion");
        Persona persona = new Persona();
        persona.setIdentificacion(identificacion);
        try {
            controlGestor.buscarPersona(persona);
            info = "<div class=\"table\"><form id=\"form2\">";
            info += "<table class=\"listing form\" cellpadding=\"0\" cellspacing=\"0\">";
            info += "<tr><td><strong>Nombre Completo:</strong></td><td><input type=\"text\" class=\"text\" name=\"nombreCompleto\" id=\"nombreCompleto\" value=\"" + persona.getNombre() + "\"/></td></tr>";
            info += "<tr><td><strong>Fecha Nacimiento:</strong></td><td><input type=\"text\" class=\"text\" name=\"fechaNacimiento\" id=\"fechaNacimiento\"value=\"" + String.valueOf(persona.getFechaNacimiento()) + "\"/></td></tr>";
            info += "<tr><td><strong>Tel&eacute;fono Habitaci&oacute;n:</strong></td><td><input type=\"text\" class=\"text\" name=\"telHabitacion\" id=\"telHabitacion\" value=\"" + persona.getTelefonoHabitacion() + "\"/></td></tr>";
            info += "<tr><td><strong>Tel&eacute;fono Oficina:</strong></td><td><input type=\"text\" class=\"text\" name=\"telOficina\" id=\"telOficina\" value=\"" + persona.getTelefonoOficina() + "\"/></td></tr>";
            info += "<tr><td><strong>Tel&eacute;fono Celular:</strong></td><td><input type=\"text\" class=\"text\" name=\"telCelular\" id=\"telCelular\" value=\"" + persona.getTelefonoCelular() + "\"/></td></tr>";
            info += "<tr><td><strong>Correo Electr&oacute;nico:</strong></td><td><input type=\"text\" class=\"text\" name=\"correo\" id=\"correo\" value=\"" + persona.getCorreoElectronico() + "\"/></td></tr>";
            info += "<tr><td><strong>Direcci&oacute;n:</strong></td><td><textarea rows=\"7\" cols=\"45\" class=\"text\" name=\"direccion\" id=\"direccion\">" + persona.getDireccion() + "</textarea></td></tr></table>";
            info += "<div class=\"boton\" align=\"right\"><a><input type=\"button\" name=\"guardar\" class=\"boton\" value=\"Guardar\" onclick=\"return modificarPersona();\"/></a><a><input type=\"reset\" name=\"cancelar\" value=\"Cancelar\" class=\"boton\"/></a></form></div>";
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            info = "";
            info = "<p><strong>No existen coincidencias</strong><p>";
        } finally {
            out.println(info);
            out.close();
        }
    }

    private void listarPersona(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String info = "";
        int tipo = Integer.parseInt(request.getParameter("tipo"));
        try {
            Thread.sleep(1000);
            ArrayList<Persona> lista = controlGestor.listarPersonaTipo(tipo);
            response.setStatus(HttpServletResponse.SC_OK);
            if (lista.size() > 0) {
                info = "<div class=\"table\"> ";
                if (tipo == 1) {
                    info += "<p><strong>Informacion de los Estudiantes</strong></p>"
                            + "<table class=\"listing\" cellpadding=\"0\" cellspacing=\"0\">";
                } else if (tipo == 2) {
                    info += "<p><strong>Informacion de los Funcionarios</strong></p>"
                            + "<table class=\"listing\" cellpadding=\"0\" cellspacing=\"0\">";
                }
                info += "<tr><th>Identificaci&oacute;n</th><th>Nombre Completo</th><th>Fecha de Nacimiento</th><th>Tel&eacute;fono Habitaci&oacute;n</th><th>Tel&eacute;fono Oficina</th><th>Tel&eacute;fono Celular</th><th>Correo Electr&oacute;nico</th><th>Direcci&oacute;n</th></tr>";
                for (int i = 0; i < lista.size(); i++) {
                    info += "<tr><td>" + lista.get(i).getIdentificacion() + "</td><td>" + lista.get(i).getNombre() + "</td><td>" + String.valueOf(lista.get(i).getFechaNacimiento()) + "</td><td>" + lista.get(i).getTelefonoHabitacion() + "</td><td>" + lista.get(i).getTelefonoOficina() + "</td><td>" + lista.get(i).getTelefonoCelular() + "</td><td>" + lista.get(i).getCorreoElectronico() + "</td><td>" + lista.get(i).getDireccion() + "</td></tr>";
                }
                info += "</table></div>";
            } else {
                info = "<p><strong>No existen registros</strong></p>";
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            info = "<p><strong>No existen registros</strong></p>";
        } finally {
            out.println(info);
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
